﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using log4net.Config;
using NPOI.POIFS.Properties;
using Pipelines.Sockets.Unofficial.Arenas;
using SqlSugar;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 分电箱、开关等（By YuXH）
    /// </summary>
    [HandlerApiLogin(FilterMode.Enforce)]
    [TokenAuthorize]
    public class PDBApiController : WebApiControllerBase
    {
        #region 模块对象
        private ec_CircuitBreakerBLL ec_CircuitBreakerBLL = new ec_CircuitBreakerBLL();
        private ec_CircuitBreakerService serv = new ec_CircuitBreakerService();
        #endregion

        #region 开关相关
        /// <summary>
        /// 查询某个分电箱下的所有开关
        /// </summary>
        /// <param name="projId"></param>
        /// <param name="RelTypeId">关联关系的id</param>
        /// <param name="PBDId">分电箱的工程ID</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetBreakers(string projId, string PDBId)
        {
            var res = ec_CircuitBreakerBLL.GetBreakersUnderPDB(projId, PDBId);
            return Success(res);
        }
        /// <summary>
        /// 批量保存（增、改）开关。传入集合。同时建立和rel。
        /// </summary> 
        /// <param name="projId"></param>
        /// <param name="PDBId">分电箱的工程ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SaveBreakers(string projId, string PDBId)
        {

            try
            {
                ec_enginedata_relBLL ec_Enginedata_RelBLL = new ec_enginedata_relBLL();
                var ec_RelTypeBll = new ec_reltypeBLL();
                var asyncContent = Request.Content.ReadAsStringAsync().Result;
                var CBs = asyncContent.ToObject<List<ec_CircuitBreakerEntity>>();
                //var RelType = ec_RelTypeBll.GetList("{\"ProjectId\":\"" + projId + "\", \"RelType\": \"" + (int)enum_RelType.开关_电缆 + "\"}").FirstOrDefault();

                foreach (var CB in CBs)
                {
                    var id = CB.EngineerDataID;

                    if (CB.CableIDs != null && CB.CableIDs.Count > 0)//目前就只考虑一个
                    {
                        CB.CableID = CB.CableIDs.First();  //string.Join(",", CB.CableIDs);
                    }

                    ec_CircuitBreakerBLL.SaveEntity(projId, ref id, CB, PDBId);  //保存开关本身
                    CB.EngineerDataID = id;

                    //if (CB.CableIDs != null)
                    //{
                    //    ec_Enginedata_RelBLL.SaveEntitys(projId, RelType.RelTypeID, item.EngineerDataID, item.CableIDs); // 建立关系（开关 和 电缆）
                    //}

                    //感觉都不需要存。因为知道开关和设备的关系，设备和   
                }
                //2024 04 11 改为 ec circuit breaker里的PDBID属性来存
                //var NewIDs = entity.Select(x => x.EngineerDataID).ToList();
                //RelType = null;
                //RelType = ec_RelTypeBll.GetList("{\"ProjectId\":\"" + projId + "\", \"RelType\": \"" + (int)enum_RelType.分电箱_开关 + "\"}").FirstOrDefault();
                //if (RelType != null)
                //{
                //ec_Enginedata_RelBLL.SaveEntitys(projId, RelType.RelTypeID, PDBId, NewIDs); // 建立关系(分电箱 和 开关）
                //}


                return Success(CBs);
            }
            catch (Exception e)
            {

                return Fail(e.Message);
            }
        }

        /// <summary>
        /// 批量保存开关箱内部开关和电缆的关联关系（也属于<see cref="SaveBreakers(string, string)"/>的一部分）。
        /// 设备和电缆的关联关系走的是RelApi下的那个SaveCableConn
        /// </summary> 
        /// <param name="projId"></param>
        /// <param name="Breakers">集合（CableID和EngineerDataID）</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SaveCableConn(string projId, [FromBody] IEnumerable<ec_CircuitBreakerEntity> Breakers)
        {

            try
            {
                if (Breakers == null) { return Success("OK"); }


                var tb_Break = ProjectSugar.TableName<ec_CircuitBreakerEntity>(projId);
                var tb_Enginee = ProjectSugar.TableName<ec_enginedataEntity>(projId);
                foreach (var objFromHttp in Breakers)
                {
                    var id = objFromHttp.EngineerDataID;
                    var CB = SqlSugarHelper.Db.Queryable<ec_CircuitBreakerEntity>().AS(tb_Break).First(x => x.EngineerDataID == id);//已有的
                    if (CB != null)
                    {
                        if (!string.IsNullOrEmpty(objFromHttp.CableName))//目前就只考虑一个
                        {
                            var cable = SqlSugarHelper.Db.Queryable<ec_enginedataEntity>().AS(tb_Enginee).First(x => x.TagNumber == objFromHttp.CableName);//已有的
                            if (cable != null)
                            {
                                CB.CableID = cable.EngineDataID;
                                ec_CircuitBreakerBLL.SaveEntity(projId, ref id, CB, CB.PDBId);  //保存开关本身
                            }

                        }


                    }

                }

                return Success("OK");
            }
            catch (Exception e)
            {

                return Fail(e.Message);
            }
        }


        /// <summary>
        /// 删除开关
        /// </summary> 
        /// <param name="projId"></param>
        /// <param name="BreakerIDs">删除多个</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult Delete(string projId, string RelTypeId, string PDBId, string BreakerIDs)
        {

            try
            {
                var IDs = BreakerIDs.Split(',');
                ec_enginedata_relBLL ec_Enginedata_RelBLL = new ec_enginedata_relBLL();
                foreach (var Id in IDs)
                {
                    ec_CircuitBreakerBLL.DeleteEntity(projId, Id);
                    ec_Enginedata_RelBLL.DeleteEntity(projId, RelTypeId, PDBId, BreakerIDs);
                }

                return Success("OK");
            }
            catch (Exception e)
            {

                return Fail(e.Message);
            }
        }
        #endregion
    }
}